package com.xxmw.transaction.service.app.impl;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import com.xxmw.transaction.common.excep.service.TransactionException;
import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.xxmw.transaction.common.utils.Constant;
import com.xxmw.transaction.common.utils.StringUtil;
import com.xxmw.transaction.service.app.MessageService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service("messageService")
public class MessageServiceImpl implements MessageService, ApplicationContextAware {
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	private String activeProfile;

	@Autowired
	private RestTemplate restTemplate;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		activeProfile = applicationContext.getEnvironment().getActiveProfiles()[0];
	}

	@Override
	public void send(String username, int type) {
		String code = StringUtil.code(6);
		JSONObject object = new JSONObject();
		object.put("code", code);
		if (!"dev".equals(activeProfile)) {
			code = sendMessage(username);
			/*switch(type) {
				case Constant.Text.LOGIN:
					send(Constant.Text.LOGIN_TEMPLATE, object.toJSONString(), username);
					break;
				case Constant.Text.SIGN:
					break;
				case Constant.Text.UPDATE:
					break;
				case Constant.Text.OTHER:
					break;
				default:
			}*/
		} else {
			code = "666666";
		}
		redisTemplate.opsForValue().set(username+type, code, 5, TimeUnit.MINUTES);
	}
	
	@Override
	@Deprecated
	public boolean send(String smsTemplate, String message, String... username) {
		boolean send = false;
		try {
			System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
			System.setProperty("sun.net.client.defaultReadTimeout", "10000");
			final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
			final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
			final String accessKeyId = "LTAIOz6eB8yaaqSA";//你的accessKeyId,参考本文档步骤2
			final String accessKeySecret = "fDOQHP4efzwh7W2WvLisLY8roH4yN9";//你的accessKeySecret，参考本文档步骤2
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,accessKeySecret);
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
			IAcsClient acsClient = new DefaultAcsClient(profile);
			//组装请求对象
			SendSmsRequest request = new SendSmsRequest();
			//使用post提交
			request.setMethod(MethodType.POST);
			//必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000”
			request.setPhoneNumbers(String.join(",", username));
			request.setSignName("");
			request.setTemplateCode(smsTemplate);
			request.setTemplateParam(message);
			SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
			if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
				//请求成功
				send = true;
				log.info(String.format("验证码发送成功! param : {}, mobile : {}",message, Arrays.toString(username)));
			}
		} catch (Exception e) {
			send = false;
			log.error("aiyun 短信发送异常!", e);
		}
		return send;
	}

	@Override
	public String get(String username, int type) {
		return redisTemplate.opsForValue().get(username + type);
	}

    @Override
    public Boolean verify(String username, int type, String code) {
        if(!code.matches("\\d{6}")) {
            throw new TransactionException("验证码格式有误,请重新输入!");
        }
        String cacheCode = get(username, type);
        if(cacheCode == null) {
            throw new TransactionException("验证码已失效!");
        }
        if(!cacheCode.equals(code)) {
            throw new TransactionException("验证码不正确,请重新输入!");
        }
        return true;
    }

	@Override
	public void clean(String username, int type) {
		redisTemplate.delete(username + type);
	}

	private String sendMessage (String username) {
		String response;
		try {
			response = restTemplate.getForObject("http://47.96.238.105:12307/proxy/note?phone="+username, String.class);
			JSONObject parseObject = JSONObject.parseObject(response);
			if("OK".equals(parseObject.getString("msg"))) {
				return parseObject.getString("result");
			}
		} catch(Exception e) {
			log.error("短信发送异常",e);
		}
		return null;
	}


}
